package com.ivan.stu.notetool.network.intercepter;

import android.util.Log;


import com.ivan.stu.notetool.utils.ConstrantManager;
import com.ivan.stu.notetool.utils.EncryptUtil;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * Created by IVAN on 2018/11/12.
 */

public class MyRequestHeaderInterceptory implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {

            String url = chain.request().url().toString();
            Log.e("url",url);

            if (url.contains("V2")&&url.contains("Notes")&&!url.contains("UploadNoteSourceInfo")){  //需要加密的请求  ||(url.contains("NoteTool")&& !url.contains("?"))

                Request request = chain.request();
                RequestBody body = request.body();
                Buffer buffer = new Buffer();
                body.writeTo(buffer);
                Charset charset = Charset.forName("UTF-8");
                MediaType contentType = body.contentType();
                if (contentType != null) {
                    charset = contentType.charset(charset);
                }
                String paramsStr = buffer.readString(charset);

                Log.e("加密后的post内容",paramsStr);

                Request originalRequest = chain.request();
                Request updateRequest = null;

                String salt = ConstrantManager.Token;
                String AppKey = ConstrantManager.childUserID;
                String toData = paramsStr;
                String sign = EncryptUtil.md5(AppKey+salt+toData);

                Log.e("salt",salt);
                Log.e("appKey",AppKey);
                Log.e("sign",sign);

                updateRequest = originalRequest.newBuilder()
                        .header("platform", AppKey)
                        .header("timestamp", salt)
                        .header("sign",sign)
                        .build();

                return chain.proceed(updateRequest);

            }else {   //不需要加密的请求

                Request request = chain.request();
                return chain.proceed(request);
            }

        }

}
